/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.auth.sys.service.impl;

import com.arisgo.cloud.auth.sys.entity.Role;
import com.arisgo.cloud.auth.sys.entity.User;
import com.arisgo.cloud.auth.sys.entity.UserRole;
import com.arisgo.cloud.auth.sys.mapper.RoleMapper;
import com.arisgo.cloud.auth.sys.mapper.UserMapper;
import com.arisgo.cloud.auth.sys.mapper.UserRoleMapper;
import com.arisgo.cloud.auth.sys.service.UserRoleService;
import com.arisgo.cloud.auth.sys.vo.RoleVo;
import com.arisgo.cloud.auth.sys.vo.UserRoleVo;
import com.arisgo.cloud.auth.sys.vo.UserVo;
import com.arisgo.cloud.common.Pagination;
import com.arisgo.cloud.common.utils.AssertUtil;
import com.arisgo.cloud.web.mybatis.service.CloudServiceImpl;
import com.arisgo.cloud.web.param.Paging;
import com.arisgo.cloud.web.param.Param;
import com.arisgo.cloud.web.param.Search;
import com.arisgo.cloud.web.utils.RequestUtil;
import com.google.common.collect.Lists;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 用户角色
 *
 * @author Arisgo
 * @since 2024-08-03
 */
@Service
@AllArgsConstructor
public class UserRoleServiceImpl extends CloudServiceImpl<UserRoleMapper, UserRole, UserRoleVo> implements UserRoleService {

    @Override
    public UserRole getInstanceModel() {
        return new UserRole();
    }

    @Override
    public UserRoleVo getInstanceVo() {
        return new UserRoleVo();
    }

    private final UserMapper userMapper;

    private final RoleMapper roleMapper;


    @Override
    public Pagination<RoleVo> pageUserRole(Long userId, Paging paging) {
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.USER_ID, userId), Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        List<UserRole> relations = mapper.selectListByQuery(wrapper);
        if (CollectionUtils.isEmpty(relations)) {
            return Pagination.defaultPage();
        }
        paging.addParam(Param.creator(Role.ID, "IN", relations.stream().map(UserRole::getRoleId).toList()));
        Page<Role> page = roleMapper.paginate(paging.getPageNo(), paging.getPageSize(), paging.buildWrapper());
        return Pagination.creator(page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow(), convert(page.getRecords(), RoleVo.class));
    }

    @Override
    public List<RoleVo> findUserRole(Long userId, Long tenantId) {
        return this.mapper.findUserRole(userId, tenantId);
    }

    @Override
    public Boolean saveUserRole(Long userId, List<Long> roleIds) {
        AssertUtil.notNull(userId, "参数异常");
        Long tenantId = RequestUtil.getTenantId();
        // 删除所有已存在的角色关系
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.USER_ID, userId), Param.creator(UserRole.TENANT_ID, tenantId))
                .buildWrapper(wrapper);
        this.mapper.deleteByQuery(wrapper);
        if (CollectionUtils.isEmpty(roleIds)) {
            return true;
        }
        // 新增角色关系
        List<UserRole> data = Lists.newArrayList();
        for (Long roleId : roleIds) {
            UserRole model = new UserRole();
            model.setUserId(userId);
            model.setRoleId(roleId);
            model.setTenantId(tenantId);
            data.add(model);
        }
        return mapper.insertBatch(data) > 0;
    }

    @Override
    public Boolean removeUserRole(Long userId, List<Long> roleIds) {
        AssertUtil.notNull(roleIds, "参数异常");
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.USER_ID, userId),
                Param.creator(UserRole.ROLE_ID, "IN", roleIds),
                Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        return mapper.deleteByQuery(wrapper) > 0;
    }

    @Override
    public Pagination<UserVo> pageRoleUser(Long roleId, Paging paging) {
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.ROLE_ID, roleId), Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        List<UserRole> relations = mapper.selectListByQuery(wrapper);
        if (CollectionUtils.isEmpty(relations)) {
            return Pagination.defaultPage();
        }
        paging.addParam(Param.creator(User.ID, "IN", relations.stream().map(UserRole::getUserId).toList()));
        Page<User> page = userMapper.paginate(paging.getPageNo(), paging.getPageSize(), paging.buildWrapper());
        return Pagination.creator(page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow(), convert(page.getRecords(), UserVo.class));
    }

    @Override
    public List<UserVo> findRoleUser(Long roleId, Search search) {
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.ROLE_ID, roleId), Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        List<UserRole> relations = mapper.selectListByQuery(wrapper);
        if (CollectionUtils.isEmpty(relations)) {
            return Collections.emptyList();
        }
        search.addParam(Param.creator(User.ID, "IN", relations.stream().map(UserRole::getUserId).toList()));
        return convert(userMapper.selectListByQuery(search.buildWrapper()), UserVo.class);
    }

    @Override
    public Boolean saveRoleUser(Long roleId, List<Long> userIds) {
        AssertUtil.notNull(roleId, "参数异常");
        Long tenantId = RequestUtil.getTenantId();
        // 删除所有已存在的角色关系
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.ROLE_ID, roleId), Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        this.mapper.deleteByQuery(wrapper);
        if (CollectionUtils.isEmpty(userIds)) {
            return true;
        }
        List<UserRole> data = Lists.newArrayList();
        for (Long userId : userIds) {
            UserRole model = new UserRole();
            model.setRoleId(roleId);
            model.setUserId(userId);
            model.setTenantId(tenantId);
            data.add(model);
        }
        return mapper.insertBatch(data) > 0;
    }

    @Override
    public Boolean removeRoleUser(Long roleId, List<Long> userIds) {
        AssertUtil.notNull(userIds, "参数异常");
        QueryWrapper wrapper = new QueryWrapper();
        Search.creator(Param.creator(UserRole.ROLE_ID, roleId),
                Param.creator(UserRole.USER_ID, "IN", userIds),
                Param.creator(UserRole.TENANT_ID, RequestUtil.getTenantId()))
                .buildWrapper(wrapper);
        return mapper.deleteByQuery(wrapper) > 0;
    }

}
